/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-10 10:32:55
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-02-26 15:50:31
 * @FilePath: \cxl-driving-training\src\store\user.store.ts
 */
import { defineStore } from 'pinia'
import { storage } from './sessionStorage'
import { login } from '@/apis/login'
import { CountDown } from '@/utils'
import { drivingSchoolSimpleList } from '@/apis/drivingSchool'

interface storeInterface {
    token: string
    company: string
    companyId: string
    customerNo: string
    name: string
    userId: string
    account: string
    isSuperAdmin: boolean
    permission: boolean
    drivingSchoolSimple: Map<string, any>
    icons: string[]
}

export const userStore = defineStore('user', {
    state: (): storeInterface => {
        return {
            token: '',
            company: '',
            companyId: '',
            customerNo: '',
            name: '',
            userId: '',
            account: '',
            isSuperAdmin: false,
            permission: true,
            drivingSchoolSimple: new Map(),
            icons: []
        }
    },
    actions: {
        resetData() {
            this.token = ''
            this.company = ''
            this.companyId = ''
            this.customerNo = ''
            this.userId = ''
            this.isSuperAdmin = false
            this.account = ''
            this.permission = true
            this.name = ''
            this.icons = []
        },
        /**
         * 保存token
         * @param token
         */
        setToken(token: string) {
            this.token = token
            //缓存token 判断token是否为空，为空则删除本地缓存
            token ? storage.set('token', token) : storage.remove('token')
        },
        /**
         * 调用登录接口
         * @param phone
         * @param password
         * @returns
         */
        async login(phone: string, password: string) {
            return new Promise((resolve, reject) => {
                login(phone, password)
                    .then((res: any) => {
                        if (Number(res.data.code) === 200) {
                            resolve(res.data)
                            this.setToken(res.data.result.accessToken)
                            storage.set('loginTime', new Date().getTime().toString())
                            storage.set('refreshToken', res.data.result.refreshToken)
                            //提前50s获取token
                            storage.set('expire', (res.data.result.expire - 50).toString())
                            //倒计时请求刷新token
                            new CountDown((res.data.result.expire - 50) / 1).start(() => {
                                console.log('开始请求刷新token')
                            })
                        } else {
                            reject(res.data)
                        }
                    })
                    .catch(err => {
                        reject(err)
                    })
            })
        },
        queryDrivingSchoolSimple(callback = (arg: Map<string, any>) => {}) {
            if (!this.token) {
                return false
            }
            /**
             * 1、判断store中 drivingSchoolSimple 是否保存了教练数据
             * 2、如果 drivingSchoolSimple 为空，则想本地数据拉取
             * 3、本地数据为空，则向服务器拉取数据
             */

            if (this.drivingSchoolSimple.size === 0) {
                const list = storage.get('drivingSchoolSimple')
                if (list) {
                    const result = JSON.parse(list)
                    result.forEach((item: any) => {
                        this.drivingSchoolSimple.set(item.id, item)
                    })
                    callback(this.drivingSchoolSimple)
                } else {
                    drivingSchoolSimpleList().then((res: any) => {
                        if (Number(res.data.code) === 200) {
                            storage.set('drivingSchoolSimple', JSON.stringify(res.data.result))
                            res.data.result.forEach((item: any) => {
                                this.drivingSchoolSimple.set(item.id, item)
                            })
                            callback(this.drivingSchoolSimple)
                        }
                    })
                }
            } else {
                callback(this.drivingSchoolSimple)
            }
        },
        updateDrivingSchoolSimple() {
            //修改驾校时，更新本地驾校列表
            this.drivingSchoolSimple.clear()
            storage.remove('drivingSchoolSimple')
            this.queryDrivingSchoolSimple()
        }
    }
})
